package cn.pjz.utils;

import com.univocity.parsers.common.processor.BeanListProcessor;
import com.univocity.parsers.csv.CsvFormat;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Collections;
import java.util.List;

public class FileUtil {

    /**
     * 读取crv文件并转换成List
     *
     * @param separator crv文件分隔符
     * @param file      待读取文件
     * @return crv对象list
     */
    public static <T> List<T> read(String separator, File file, Class<T> clazz) {
        List<T> result = Collections.emptyList();
        try {
            BeanListProcessor<T> rowProcessor = new BeanListProcessor<>(clazz);
            //设置分隔符
            CsvFormat csvFormat = new CsvFormat();
            csvFormat.setDelimiter(separator);

            CsvParserSettings parserSettings = new CsvParserSettings();
            parserSettings.setProcessor(rowProcessor);
            parserSettings.setFormat(csvFormat);

            CsvParser parser = new CsvParser(parserSettings);
            InputStream in = Files.newInputStream(file.toPath());
            parser.parse(in);
            //逐行读取
            result = rowProcessor.getBeans();
        } catch (Exception e) {
            return result;
        }
        return result;
    }



    public File multipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀(.xml)
        String suffix = null;
        if (fileName != null) {
            suffix = fileName.substring(fileName.lastIndexOf("."));
        }
        // 若要防止生成的临时文件重复,需要在文件名后添加随机码
        try {
            //"tmp", ".txt"
            //fileName这块可以根据自己的业务需求进行修改，我这里没有做任何处理
            File file = null;
            if (fileName != null) {
                file = File.createTempFile(fileName, suffix);
            }
            if (file != null) {
                multiFile.transferTo(file);
            }
            return file;
        } catch (Exception e) {
            return null;
        }
    }
}
